package com.hsc.www.springCache.service;

import com.hsc.www.springCache.entity.User;
import com.hsc.www.springCache.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImp implements UserService {

    @Autowired
    UserMapper userMapper;

    @Cacheable(value = "UserCache", key = "'getAll'")
    @Override
    public List<User> getAll() {
        return userMapper.getAll();
    }

    @Cacheable(value = "UserCache", key = "'userId:'+#id")
    @Override
    public User selectById(Integer id) {
        return userMapper.selectById(id);
    }

    @CacheEvict(value = "UserCache", allEntries = true)
    @Override
    public int updateById(User user) {
        return userMapper.updateById(user);
    }

    @CacheEvict(value = "UserCache", allEntries = true)
    @Override
    public int insert(User user) {
        return userMapper.insert(user);
    }

    @CacheEvict(value = "UserCache", allEntries = true)
    @Override
    public int deleteById(Integer id) {
        return userMapper.deleteById(id);
    }

    @Override
    @CacheEvict(value = "UserCache", key = "'userId:'+#user.id")
    @Cacheable(value = "UserCache", key = "'userId:'+#user.id")
    @CachePut(value = "UserCache", key = "'userId:'+#user.id")
    public User updateByIdAndSelect(User user) {
        System.out.println("updateByIdAndSelect");
        int result = userMapper.updateById(user);
        if (result == 1) {
            return userMapper.selectById(user.getId());
        } else {
            return null;
        }
    }


}
